package org.lc.stk.service.question.impl;

import java.util.List;

import org.lc.stk.dao.question.QuestionTypeRepository;
import org.lc.stk.model.question.attrs.QuestionType;
import org.lc.stk.service.exception.BusinessException;
import org.lc.stk.service.question.QuestionTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class QuestionTypeServiceImpl implements QuestionTypeService {

    @Autowired
    private QuestionTypeRepository questionTypeRepository;

    @Override
    @Transactional
    public QuestionType create(QuestionType questionType) {
        // 验证名称是否重复
        if (existsByName(questionType.getName(), null)) {
            throw new BusinessException("题型名称已存在");
        }
        return questionTypeRepository.save(questionType);
    }

    @Override
    @Transactional
    public QuestionType update(QuestionType questionType) {
        if (!questionTypeRepository.existsById(questionType.getId())) {
            throw new BusinessException("题型不存在");
        }

        // 验证名称是否重复
        if (existsByName(questionType.getName(), questionType.getId())) {
            throw new BusinessException("题型名称已存在");
        }

        return questionTypeRepository.save(questionType);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        if (!questionTypeRepository.existsById(id)) {
            throw new BusinessException("题型不存在");
        }
        
        // TODO: 检查题型是否被使用
        questionTypeRepository.deleteById(id);
    }

    @Override
    public QuestionType findById(Long id) {
        return questionTypeRepository.findById(id)
            .orElseThrow(() -> new BusinessException("题型不存在"));
    }

    @Override
    public List<QuestionType> findAll() {
        return questionTypeRepository.findAll();
    }

    @Override
    public boolean existsByName(String name, Long excludeId) {
        return questionTypeRepository.existsByNameAndIdNot(name, excludeId);
    }

    @Override
    public List<QuestionType> findAllSystemTypes() {
        return questionTypeRepository.findAllSystemTypes();
    }

    @Override
    public List<QuestionType> findAllUserDefinedTypes() {
        return questionTypeRepository.findAllUserDefinedTypes();
    }

    @Override
    public boolean existsAll(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return true;
        }
        return questionTypeRepository.existsAllByIds(ids, ids.size());
    }
}